package com.console.front.dao.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.console.front.dao.UserDao;
import com.console.front.model.MovsModel;
import com.console.front.model.UserModel;

@Repository("userDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
	
	@Override
	public UserModel get(Long id) {
		return getHibernateTemplate().get(UserModel.class, id);
	}

	@Override
	public void save(UserModel user) {
		getHibernateTemplate().save(user);
	}

	@Override
	public UserModel login(String username, String password) {
		List<UserModel> models = (List<UserModel>) getHibernateTemplate().find("FROM UserModel user WHERE user.username = ? AND user.password = ?",username,password);
		if(models.size() > 0){
			return models.get(0);
		}
		return null;
	}

	@Override
	public void initMovs(MovsModel model) {
		getHibernateTemplate().save(model);
	}

	@Override
	public List<MovsModel> findMovs(int pageNum, int pageSize) {
		List<MovsModel> models = new ArrayList<MovsModel>();
		
		Query query = getSessionFactory().getCurrentSession().createQuery("FROM MovsModel ORDER BY id DESC");
		query.setFirstResult((pageNum-1) * pageSize);
		query.setMaxResults(pageSize);
		models = query.list();
		
		for(MovsModel model : models){
			System.out.println(model.id + "---" + model.name);
		}
		
		return models;
	}

	@Override
	public String findMovsMp4(String movsPath) {
		ArrayList<String> linksList = findAllLinks(movsPath);
		for(String mp4Link : linksList){
			if(mp4Link.contains(".mp4")){
				return mp4Link;
			}
		}
		return "";
	}
	
	private ArrayList<String> findAllLinks(String url){
		ArrayList<String> linksList = new ArrayList<String>();
		try {
			Connection connection = Jsoup.connect(url);
			connection.timeout(10 * 1000);
			Document doc = connection.get();
			
			Elements links = doc.select("a[href]");
	        Elements media = doc.select("[src]");
	        Elements imports = doc.select("link[href]");
	        
	        for (Element src : media) {
	        	linksList.add(src.attr("abs:src"));
	        }
	        for (Element link : imports) {
	        	linksList.add(link.attr("abs:href"));
	        }
	        for (Element link : links) {
	        	linksList.add(link.attr("abs:href"));
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return linksList; 
	}

	@Override
	public void updateNewData(MovsModel model) {
		if(getHibernateTemplate().find("FROM MovsModel m WHERE m.name = ?", model.name).size() > 0)
			return;
		getHibernateTemplate().save(model);
		System.out.println(model.name + "不存在,已保存!");
	}

	@Override
	public UserModel recharge(String days,String uid) {
		UserModel uModel = getHibernateTemplate().get(UserModel.class,Long.parseLong(uid));
		try{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String expireTime = uModel.getExpire_time();	//格式：yyyy-MM-dd
			Date date = null;
			if(expireTime == null){
				//没有充值过
				date = new Date();
				Calendar calendar = Calendar.getInstance();
				calendar.add(Calendar.DAY_OF_YEAR, Integer.parseInt(days));
				date = calendar.getTime();
			}else{
				//以前充值过
				date = sdf.parse(expireTime);
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(date);
				calendar.add(Calendar.DAY_OF_YEAR, Integer.parseInt(days));
				date = calendar.getTime();
			}
			uModel.setExpire_time(sdf.format(date));
			getHibernateTemplate().save(uModel);
			return uModel;
		}catch(Exception e){
			e.printStackTrace();
			uModel.setId(0l);
			return uModel;
		}
	}

	@Override
	public UserModel reg(String username, String password) {
		List<UserModel> models = (List<UserModel>) getHibernateTemplate().find("FROM UserModel user WHERE user.username = ?",username);
		if(models.size() > 0)
			return null;

		UserModel model = new UserModel();
		model.setUsername(username);
		model.setPassword(password);
		getHibernateTemplate().save(model);
		
		return model;
	}
	
}
